package com.open.capacity.tenant.controller;

import cn.hutool.core.util.StrUtil;
import com.open.capacity.common.web.Result;
import com.open.capacity.log.annotation.LogAnnotation;
import com.open.capacity.tenant.dao.entity.Tenant;
import com.open.capacity.tenant.model.UpdateTenantDto;
import com.open.capacity.tenant.service.TenantService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * 管理员控制层
 * @program: open-capacity-platform
 * @author: GuoGaoJu
 * @create: 2023-03-21
 **/
@RestController
@RequestMapping("/admin")
@Api(value = "管理员操作")
@Valid
@Slf4j
public class AdminController {

    @Autowired
    private TenantService tenantService;

    @Autowired
    private RedisTemplate redisTemplate;

    //1.管理员登录
    /**
     * security登录接口/login
     * POST 表单参数：username,password
     * 响应：
     * {
     *     "access_token": "xxxxxx",
     *     "create_time": 1680747051955,
     *     "type": "bearer",
     *     "expires_time": 1680754251955,
     *     "username": "test"
     * }
     */


    //2.管理员更新租户状态
    @PreAuthorize("hasAuthority('admin')")
    @PostMapping("/tenant")
    @ApiOperation(value = "管理员更新租户状态（1-申请中、2-活跃、3-注销）")
    @LogAnnotation(module = "tenant-server",recordRequestParam = false)
    public Result updateTenantStatus(@RequestBody @Valid UpdateTenantDto updateTenantDto){
        return tenantService.updateTenantStatus(updateTenantDto);
    }

    //3.管理员退出登录
    @ApiOperation(value = "管理员登出")
    @PreAuthorize("hasAuthority('admin')")
    @PostMapping("/doLogout")
    @LogAnnotation(module = "tenant-server")
    public String logout(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("Authorization");
        if (!StrUtil.isBlank(token)){
            String jwt = token.replaceAll("bearer ", "");
            if (!StrUtil.hasBlank(jwt)){

                Boolean aBoolean = redisTemplate.hasKey("token:" + jwt);
                log.info("是否存在key? "+aBoolean);

                Boolean delete = redisTemplate.delete("token:" + jwt);
                log.info(jwt+"删除结果："+delete);

                Boolean aBoolean1 = redisTemplate.hasKey("token:" + jwt);
                log.info("是否存在key? "+aBoolean1);

                return "登出成功";
            }
        }
        return "登出失败";
    }

    //4.管理员查询租户列表
    @PreAuthorize("hasAuthority('admin')")
    @GetMapping("/tenants")
    @ApiOperation(value = "查询所租户列表")
    @LogAnnotation(module = "tenant-server")
    public Result<List<Tenant>> queryTenantList(){
        return tenantService.queryTenantList();
    }

}
